import axios from 'axios'
import { ElMessage } from 'element-plus'
import { router } from "../main.js";
import Cookies from 'js-cookie'

const logout = () => {
    console.log("logout...");
    router.push("/login");
};

const service = axios.create({
    baseURL: 'http://60.205.112.120:9093',
    timeout: 60000,
    withCredentials: true,
    headers: {
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
    },
})

// 添加请求拦截器
service.interceptors.request.use(
    function (config) {
        // console.log("config ",config)
        config.headers["user-id"] = Cookies.get("userid")
        return config
    },
    function (error) {
        // console.log(error)
        return Promise.reject(error)
    }
)

// 添加响应拦截器
service.interceptors.response.use(
    function (response) {
        // console.log(response)
        const dataAxios = response.data
        if (dataAxios.code === 1003) {
            console.log("未登录！")
            ElMessage({
                message: "未登录！",
                type: "warning",
                grouping: true
            })
            router.push("/login");
            Cookies.remove("userid");
            Cookies.remove("calcMode");
            console.log(router)
        }
        return dataAxios
    },
    function (error) {
        // console.log(error)
        return Promise.reject(error)
    }
)

export default service